<template>
  <div class="layout-container" style=" max-width:100%;">
    <div class="layout-container-form flex space-between">
      <div class="layout-container-form-handle">
        <el-button type="primary" :icon="Plus" @click="handleAdd">{{
          $t("message.common.add")
        }}
        </el-button>
        <el-popconfirm :title="$t('message.common.delTip')" @confirm="handleDel(chooseData)">
          <template #reference>
            <el-button type="danger" :icon="Delete" :disabled="chooseData.length === 0">{{ $t("message.common.delBat")
              }}
            </el-button>
          </template>

        </el-popconfirm>

        <el-button v-show="!editingAll" type="primary" @click="handleEditAll">
          批量编辑
        </el-button>

        <el-upload ref="uploader" action="/api/accountManagement/importStudentsFromExcel" :auto-upload="true"
          :on-change="handleStuExcelFileChange" :before-upload="beforeStuExcelFileUpload" accept=".xls, .xlsx"
          :show-file-list="false" :on-success="handleStuExcelFileSuccess" :on-progress="handleStuExcelFileProgress">
          <el-button type="primary" style="margin-left: 10px">
            <span>批量导入学生账号</span>
          </el-button>
        </el-upload>
        <el-button v-show="editingAll" type="success" @click="handleSaveAll">
          全部保存
        </el-button>

        <el-button v-show="editingAll" type="danger" @click="handleCancelEditAll">
          {{ $t("message.common.cancelBat") }}
        </el-button>

      </div>
      <div class="layout-container-form-search">
        <el-input v-model="query.input" :placeholder="$t('message.common.searchTip')"
          @change="handleInputChange(query.input)"></el-input>
        <el-button type="primary" :icon="Search" class="search-btn" @click="handleInputChange(query.input)">{{
          $t("message.common.search") }}
        </el-button>
      </div>
    </div>
    <div class="layout-container-table">
      <Table ref="table" v-model:page="page" v-loading="loading" :showSelection="true" :data="tableData"
        @getTableData="getTableData" @selection-change="handleSelectionChange" id="printContent">
        <el-table-column label="Id" align="center" fixed width="60px">
          <template v-slot="{ row, $index }">
            {{ calculateId($index) }}
          </template>
        </el-table-column>

        <el-table-column fixed prop="id" align="center" label="学号" width="120px">
          <!-- <template #default="{ row }">
            <span>{{ row.id }}</span>
          </template> -->
        </el-table-column>

        <el-table-column fixed prop="name" align="center" label="姓名">
          <template #default="{ row }">
            <span v-if="!(editingAll)">{{ row.name }}</span>
            <el-input v-else-if="editingAll" v-model="row.name" @change="addToBuffer(row)"></el-input>

          </template>
        </el-table-column>

        <el-table-column fixed prop="gender" align="center" label="性别" width="80px">
          <template #default="{ row }">
            <span v-if="!(editingAll)">{{ row.gender }}</span>
            <el-select v-else-if="editingAll" v-model="row.gender" placeholder="请选择" @change="addToBuffer(row)"
              clearable>
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </template>
        </el-table-column>


        <!-- ============================================================================= -->
        <el-table-column fixed prop="school" align="center" label="学校">
          <template #default="{ row }">
            <span v-if="!(editingAll)">{{ row.school }}</span>
            <el-select v-else-if="editingAll" v-model="row.school" filterable placeholder="选择学校"
              @focus="handleGetAllSchool(row)" @change="handleChangeSchool(row)" style="width: 240px">
              <el-option v-for="(school, index) in schoolList" :key="index" :label="school" :value="school" />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column fixed prop="college" align="center" label="学院">
          <template #default="{ row }">
            <span v-if="!(editingAll)">{{ row.college }}</span>
            <el-select v-else-if="editingAll" v-model="row.college" filterable placeholder="选择学院"
              @focus="handleGetCollege(row)" @change="handleChangeCollege(row)" :disabled="!isSchoolSelected(row)"
              style="width: 240px">
              <el-option v-for="(college, index) in collegeList" :key="index" :label="college" :value="college" />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column fixed prop="major" align="center" label="专业">
          <template #default="{ row }">
            <span v-if="!(editingAll)">{{ row.major }}</span>
            <el-select v-else-if="editingAll" v-model="row.major" filterable placeholder="选择专业"
              @change="addToBuffer(row)" @focus="handleGetMajor(row)" :disabled="!isCollegeSelected(row)"
              style="width: 240px">
              <el-option v-for="(major, index) in majorList" :key="index" :label="major" :value="major" />
            </el-select>
          </template>
        </el-table-column>
        <!-- ============================================================================= -->

        <!-- <el-table-column fixed prop="cls" align="center" label="班级" width="80px">
          <template #default="{ row }">
            <span v-if="!(editingAll)">{{ row.cls }}</span>

          </template>
        </el-table-column> -->


        <el-table-column fixed prop="phone" align="center" label="手机号" width="140px">
          <template #default="{ row }">
            <span v-if="!(editingAll)">{{ row.phone }}</span>
            <el-input v-else-if="editingAll" v-model="row.phone" @change="addToBuffer(row)"></el-input>
          </template>
        </el-table-column>

        <el-table-column fixed prop="email" align="center" label="邮箱" width="180px">
          <template #default="{ row }">
            <span v-if="!(editingAll)">{{ row.email }}</span>
            <el-input v-else-if="editingAll" v-model="row.email" @change="addToBuffer(row)"></el-input>
          </template>
        </el-table-column>

        <el-table-column :label="$t('message.common.handle')" align="center" fixed="right" width="200">
          <template #default="scope">
            <el-button @click="handleEdit(scope.row)">{{
          $t("message.common.update")
        }}
            </el-button>
            <el-popconfirm :title="$t('message.common.delTip')" @confirm="handleDel([scope.row])">
              <template #reference>
                <el-button type="danger">{{ $t("message.common.del") }}</el-button>
              </template>
            </el-popconfirm>


          </template>
        </el-table-column>
      </Table>
      <Layer :layer="layer" @getTableData="getTableData" v-if="layer.show" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import {  ref, reactive, watchEffect, onMounted } from "vue";
import { Page } from "@/components/table/type";
import {
  deleteStudentAccountsApi,
  getStudentAccountDataApi,
  updateStudentAccountsApi,
  ImportStudentsFromExcelApi,
} from "@/api/accountManagement";
import { LayerInterface } from "@/components/layer/index.vue";
import { ElMessage } from "element-plus";
import Table from "@/components/table/index.vue";
import Layer from "./layer.vue";
import { Plus, Delete, Search } from '@element-plus/icons'
import { onBeforeRouteLeave } from 'vue-router';
import { getAllSchoolApi, getCollegeBySchoolApi, getMajorByCollegeApi } from "@/api/user"

onMounted(() => {
  getTableData(true)

})
// 存储搜索用的数据
const schoolList = ref([])
const collegeList = ref([])
const majorList = ref([])

const query = reactive({
  input: "",
});
// 弹窗控制器
const layer: LayerInterface = reactive({
  show: false,
  title: "新增",
  showButton: true,
});
// 分页参数, 供table使用
const page: Page = reactive({
  index: 1,
  size: 20,
  total: 0,
});
const filter_methods = reactive({
  selector: null,
  input_str: '',
})
const loading = ref(true);
const tableData = ref([]); // 表格数据
const buffer = ref([]) // 数据缓冲区，保存待修改的数据
const chooseData = ref([]);
const editingRow = ref([]);    // 当前编辑的行
const editingAll = ref(false);
// 使用 computed 计算其他两个选择框的可选状态
const isSchoolSelected = (row: any) => {
  return row.school !== '';
};

const isCollegeSelected = (row: any) => {
  return row.school !== '' && row.college !== '';
};
const handleChangeSchool = (row: any) => {
  addToBuffer(row);
  row.college = '';
  row.major = '';
};
const handleChangeCollege = (row: any) => {
  addToBuffer(row);
  row.major = '';
};
watchEffect((row: any) => {
  if (row.school === '') {
    row.college = '';
    row.major = '';
  } else if (!isCollegeSelected(row)) {
    row.major = '';
  }
});
const handleGetAllSchool = (row: any) => {
  getAllSchoolApi().then(response => {
    schoolList.value = response.data;
  })
}
const handleGetCollege = (row: any) => {
  getCollegeBySchoolApi(row).then(response => {
    collegeList.value = response.data;
  })
}
const handleGetMajor = (row: any) => {
  getMajorByCollegeApi(row).then(response => {
    majorList.value = response.data;
  })
}
onBeforeRouteLeave((to, from, next) => {
  handleCancelEditAll();
  next();
});
const handleSelectionChange = (val: []) => {
  chooseData.value = val;
  console.log("选中：", val)
};
// 获取表格数据
// params <init> Boolean ，默认为false，用于判断是否需要初始化分页
function isEditing(row: []) {
  return editingRow.value === row;
}

const handleInputChange = (input_str: string) => {
  filter_methods.input_str = input_str;
  getTableData(true)
}
const handleStuExcelFileChange = (file: any) => {
  console.log("handleStuExcelFileChange, ", file)
}
const handleStuExcelFileSuccess = (response: any) => {
  ElMessage.success('上传成功')
}
const beforeStuExcelFileUpload = (file: any) => {
  console.log("beforeStuExcelFileUpload, ", file)

}
const handleStuExcelFileProgress = (percentage: number) => {
  console.log("handleStuExcelFileProgress, ", percentage)
}
const handleImportStudentsFromExcel = () => {
  ImportStudentsFromExcelApi({

  }).then(response => {
    console.log(response)
  })
}

function handleEditAll() {
  editingAll.value = !editingAll.value;
  editingRow.value = null; // 清空单独编辑的行
  tableData.value.forEach((row) => {
    if (row.dirty) {
      addToBuffer(row);
    }
  })
}

function addToBuffer(row: any) {
  const index = buffer.value.findIndex((item: any) => item.id === row.id);
  if (index !== -1) {
    // 根据学号匹配缓冲区中的数据，如果有相同学号则覆盖，否则加入缓冲区
    buffer.value[index] = row;
  } else {
    // 加入缓冲区
    buffer.value.push(row);
  }
}

function handleSaveAll() {
  // 处理保存逻辑
  console.log('更新前：', buffer.value)
  updateStudentAccountsApi(buffer.value).then((response: any) => {
    // 处理成功的情况
    if (response.code === 200) {
      ElMessage.success('更新成功')
    } else {
      ElMessage.error('更新失败')
    }
  }).catch(error => {
    // 处理失败的情况
    ElMessage.error(error)
  }).finally(() => {
    // 清空缓冲区和关闭编辑状态
    buffer.value = [];
    editingAll.value = false;
  });
}

function handleCancelEditAll() {
  // 处理保存逻辑
  buffer.value = [];
  editingAll.value = false;
  getTableData(true);
}

const getTableData = (init: Boolean) => {
  loading.value = true
  if (init) {
    page.index = 1
  }
  let params = {
    page: page.index,
    pageSize: page.size,
    filter_methods: filter_methods,
    ...query
  }


  getStudentAccountDataApi(params)
    .then((res) => {
      let data = res.data.data;
      data.forEach((d: any) => {
        d.loading = false;
      });
      tableData.value = data;
      page.total = res.data.total_size;
    })
    .catch((error) => {
      console.error('发生错误:', error);
      tableData.value = [];
      page.index = 1;
      page.total = 0;
    })
    .finally(() => {
      loading.value = false;
    });
}


// 删除功能
const handleDel = (data: object[]) => {
  deleteStudentAccountsApi(data).then((response: any) => {
    // 处理成功的情况
    if (response.code === 200) {
      ElMessage.success('删除成功')
    } else {
      ElMessage.error('删除失败')
    }
  }).catch(error => {
    // 处理失败的情况
    ElMessage.error(error)
  }).finally(() => {
    // // 清空缓冲区和关闭编辑状态
    getTableData(true)
  });
}
const calculateId = (index: number) => {
  // 根据 page、pagesize 和当前行的索引计算出 "Id" 列的值
  return (page.index - 1) * page.size + index + 1;
};
// 新增弹窗功能
const handleAdd = () => {
  layer.title = "新增数据";
  layer.show = true;
  delete layer.row;
}
// 编辑弹窗功能
const handleEdit = (row: any) => {
  layer.title = "编辑数据";
  layer.row = row;
  layer.show = true;
}


</script>

<style lang="scss" scoped>
.statusName {
  margin-right: 10px;
}
</style>
